require('./utils/strophe.js')
var WebIM = require('./utils/WebIM.js').default

//app.js   
App({
    getRoomPage: function () {
        return this.getPage("pages/chatroom/chatroom")
    },
    getPage: function (pageName) {
        var pages = getCurrentPages()
        return pages.find(function (page) {
            return page.__route__ == pageName
        })
    },
    onLaunch: function () {
        //调用API从本地缓存中获取数据
        var that = this
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)

        // wx.getSetting({
        //   success: function (res) {
        //     if (res.authSetting['scope.userInfo']) {
        //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称
        //       wx.getUserInfo({
        //         success: function (res) {
        //           console(res.userInfo)
        //         }
        //       })
        //     }
        //   }
        // })
        //debugger

        wx.authorize({
          scope: 'scope.userInfo',
          success(res) {
            // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
           // wx.startRecord()
            console.dir(res)

            wx.getUserInfo({
              success: function (res) {
                console(res.userInfo)
              }
            })
          }
        })


        // console.log("onLoad=====");
        // var that = this;
        // wx.getUserInfo({
        //   success: function (res) {
        //     var userInfo = res.userInfo;
        //     that.setData({
        //       nickName: userInfo.nickName,
        //       avatarUrl: userInfo.avatarUrl,
        //     })
        //   }, fail: function () {
        //     wx.showModal({
        //       title: '警告',
        //       content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
        //       success: function (res) {
        //         if (res.confirm) {
        //           wx.openSetting({
        //             success: (res) => {
        //               if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
        //                 wx.getUserInfo({
        //                   success: function (res) {
        //                     var userInfo = res.userInfo;
        //                     that.setData({
        //                       nickName: userInfo.nickName,
        //                       avatarUrl: userInfo.avatarUrl,
        //                     })
        //                   }
        //                 })
        //               }
        //             }, fail: function (res) {

        //             }
        //           })

        //         }
        //       }
        //     })
        //   }, complete: function (res) {


        //   }
        // })
        

        WebIM.conn.listen({
            onOpened: function (message) {
                WebIM.conn.setPresence()
            },
            onPresence: function (message) {
                switch(message.type){
                    case "unsubscribe":
                        pages[0].moveFriend(message);
                        break;
                    case "subscribe":
                        if (message.status === '[resp:true]') {
                            return
                        } else {
                            pages[0].handleFriendMsg(message)
                        }
                        break;
                    case "joinChatRoomSuccess":
                        console.log('Message: ', message);
                        wx.showToast({
                            title: "JoinChatRoomSuccess",
                        });
                        break;
                    case "memberJoinChatRoomSuccess":
                        console.log('memberMessage: ', message);
                        wx.showToast({
                            title: "memberJoinChatRoomSuccess",
                        });
                        break;
                    case "memberLeaveChatRoomSuccess":
                        console.log("LeaveChatRoom");
                        wx.showToast({
                            title: "leaveChatRoomSuccess",
                        });
                        break;
                }
            },
            onRoster: function (message) {
                var pages = getCurrentPages()
                if (pages[0]) {
                    pages[0].onShow()
                }
            },

            onVideoMessage: function(message){
                console.log('onVideoMessage: ', message);
                var page = that.getRoomPage()
                if (message) {
                    if (page) {
                        page.receiveVideo(message, 'video')
                    } else {
                        var chatMsg = that.globalData.chatMsg || []
                        var time = WebIM.time()
                        var msgData = {
                            info: {
                                from: message.from,
                                to: message.to
                            },
                            username: message.from,
                            yourname: message.from,
                            msg: {
                                type: 'video',
                                data: message.url
                            },
                            style: '',
                            time: time,
                            mid: 'video' + message.id
                        }
                        msgData.style = ''
                        chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
                        chatMsg.push(msgData)
                        wx.setStorage({
                            key: msgData.yourname + message.to,
                            data: chatMsg,
                            success: function () {
                                //console.log('success')
                            }
                        })
                    }
                }
            },

            onAudioMessage: function (message) {
                console.log('onAudioMessage', message)
                var page = that.getRoomPage()
                console.log(page)
                if (message) {
                    if (page) {
                        page.receiveMsg(message, 'audio')
                    } else {
                        var chatMsg = that.globalData.chatMsg || []
                        var value = WebIM.parseEmoji(message.data.replace(/\n/mg, ''))
                        var time = WebIM.time()
                        var msgData = {
                            info: {
                                from: message.from,
                                to: message.to
                            },
                            username: message.from,
                            yourname: message.from,
                            msg: {
                                type: 'audio',
                                data: value
                            },
                            style: '',
                            time: time,
                            mid: 'audio' + message.id
                        }
                        console.log("Audio msgData: ", msgData);
                        chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
                        chatMsg.push(msgData)
                        wx.setStorage({
                            key: msgData.yourname + message.to,
                            data: chatMsg,
                            success: function () {
                                //console.log('success')
                            }
                        })
                    }
                }
            },

            onLocationMessage: function (message) {
                console.log("Location message: ", message);
            },

            onTextMessage: function (message) {
                var page = that.getRoomPage()
                console.log(page)
                if (message) {
                    if (page) {
                        page.receiveMsg(message, 'txt')
                    } else {
                        var chatMsg = that.globalData.chatMsg || []
                        var value = WebIM.parseEmoji(message.data.replace(/\n/mg, ''))
                        var time = WebIM.time()
                        var msgData = {
                            info: {
                                from: message.from,
                                to: message.to
                            },
                            username: message.from,
                            yourname: message.from,
                            msg: {
                                type: 'txt',
                                data: value
                            },
                            style: '',
                            time: time,
                            mid: 'txt' + message.id
                        }
                        chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
                        chatMsg.push(msgData)
                        wx.setStorage({
                            key: msgData.yourname + message.to,
                            data: chatMsg,
                            success: function () {
                                //console.log('success')
                            }
                        })
                    }
                }
            },
            onEmojiMessage: function (message) {
                //console.log('onEmojiMessage',message)
                var page = that.getRoomPage()
                //console.log(pages)
                if (message) {
                    if (page) {
                        page.receiveMsg(message, 'emoji')
                    } else {
                        var chatMsg = that.globalData.chatMsg || []
                        var time = WebIM.time()
                        var msgData = {
                            info: {
                                from: message.from,
                                to: message.to
                            },
                            username: message.from,
                            yourname: message.from,
                            msg: {
                                type: 'emoji',
                                data: message.data
                            },
                            style: '',
                            time: time,
                            mid: 'emoji' + message.id
                        }
                        msgData.style = ''
                        chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
                        chatMsg.push(msgData)
                        //console.log(chatMsg)
                        wx.setStorage({
                            key: msgData.yourname + message.to,
                            data: chatMsg,
                            success: function () {
                                //console.log('success')
                            }
                        })
                    }
                }
            },
            onPictureMessage: function (message) {
                //console.log('Picture',message);
                var page = that.getRoomPage()
                if (message) {
                    if (page) {
                        //console.log("wdawdawdawdqwd")
                        page.receiveImage(message, 'img')
                    } else {
                        var chatMsg = that.globalData.chatMsg || []
                        var time = WebIM.time()
                        var msgData = {
                            info: {
                                from: message.from,
                                to: message.to
                            },
                            username: message.from,
                            yourname: message.from,
                            msg: {
                                type: 'img',
                                data: message.url
                            },
                            style: '',
                            time: time,
                            mid: 'img' + message.id
                        }
                        msgData.style = ''
                        chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
                        chatMsg.push(msgData)
                        wx.setStorage({
                            key: msgData.yourname + message.to,
                            data: chatMsg,
                            success: function () {
                                //console.log('success')
                            }
                        })
                    }
                }
            },
            // 各种异常
            onError: function (error) {
                // 16: server-side close the websocket connection
                if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
                    if (WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax) {
                        return;
                    }

                    wx.showToast({
                        title: 'server-side close the websocket connection',
                        duration: 1000
                    });
                    wx.redirectTo({
                        url: '../login/login'
                    });
                    return;
                }

                // 8: offline by multi login
                if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
                    wx.showToast({
                        title: 'offline by multi login',
                        duration: 1000
                    })
                    wx.redirectTo({
                        url: '../login/login'
                    })
                    return;
                }
            },
        })

        
    }
    ,
    /**
   * 授权
   * scope.userInfo wx.getUserInfo  用户信息
      scope.userLocation    wx.getLocation, wx.chooseLocation   地理位置
      scope.address wx.chooseAddress    通讯地址
      scope.invoiceTitle    wx.chooseInvoiceTitle   发票抬头
      scope.werun   wx.getWeRunData 微信运动步数
      scope.record  wx.startRecord  录音功能
      scope.writePhotosAlbum    wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum    保存到相册
      scope.camera      摄像头
   */
    checkAuthorize(scope) {
      wx.getSetting({
        success: (res) => {
          console.log(res.authSetting[scope])
          if (!res.authSetting[scope]) {
            wx.showModal({
              title: '用户未授权',
              content: '拒绝授权将不能体验小程序完整功能，点击确定开启授权',
              success: (res) => {
                console.log(res)
                if (res.confirm) {
                  wx.openSetting({success:(res)=>{
                    res.authSetting = { "scope.userInfo": true};
                  }})
                }
              }
            })
          }
        }
      })
    },

    toAuthorize: function () {
      //重新调起授权
      wx.openSetting({
        success: (res) => {
          if (res.authSetting["scope.userInfo"] && res.authSetting["scope.userLocation"]) {
           // this.setData({ authorizeInfo: true })
            //reLaunch
           
          } else {
            //this.setData({ authorizeInfo: false })
          }
        },
        fail: (res) => {
          console.log("授权失败")
        }
      })
    },

    login: function () {
      // 登录部分代码
      var that = this;
      wx.login({
        // 调用 login 获取 code
        success: function (res) {
          var code = res.code;
          wx.getUserInfo({
            // 调用 getUserInfo 获取 encryptedData 和 iv
            success: function (res) {
              // success
              that.globalData.userInfo = res.userInfo;
              var encryptedData = res.encryptedData || 'encry';
              var iv = res.iv || 'iv';
              console.log(config.basic_token);
               
            },
            fail: function () {
              // fail
            },
            complete: function () {
              // complete
            }
          })
        }
      })

    },

    getUserInfo: function (cb) {
        var that = this
        if (this.globalData.userInfo) {
            typeof cb == "function" && cb(this.globalData.userInfo)
        } else {
            //调用登录接口
          //that.checkAuthorize("scope.userInfo");
          that.toAuthorize();


          //that.login();


          


          // wx.login({
          //   success: function (res) {
          //     var code = res.code;
          //     wx.request({
          //       url: that.globalData.srvlink + "/code/h5pay/openId?code=" + code,
          //       method: 'GET',
          //       header: {
          //         'content-type': 'application/json'
          //       },
          //       success: function (openIdRes) {
          //         var wxOpenID = openIdRes.data;
          //         wx.setStorageSync('openId', wxOpenID);
          //        // console.log("openId:" + wxOpenID)
          //         var wxOpenID 
          //         // 判断openId是否获取成功
          //         if (openIdRes.data != null & openIdRes.data != undefined) {
                    
          //           wx.getUserInfo({
          //             success: function (data) {
          //               that.globalData.userInfo = data.userInfo
          //               var wxuser = {};
          //               wxuser.username = data.userInfo.nickName
          //               wxuser.wxname = data.userInfo.nickName
          //               wxuser.lockInfo = data.userInfo.avatarUrl
          //               wxuser.wxOpenId = wxOpenID  

          //               console.dir(wxuser) 

          //               // wx.request({
          //               //   url: that.globalData.srvlink + "/code/member/wx",
          //               //   method: 'POST',
          //               //   data:wxuser,
          //               //   header: {
          //               //     'content-type': 'application/json'
          //               //   },
          //               //   success: function (resData) {
          //               //     //console.dir(resData);
          //               //     wx.setStorageSync('userInfo', resData.data.data);
                            
          //               //     //cb(resData.data.data);

          //               //   },
          //               //   fail: function (failData) {
          //               //     console.info("获取用户数据失败");
          //               //   }
          //               //   });                        
          //             },
          //             fail: function (failData) {
          //               console.dir(failData);
          //               console.info("用户拒绝授权");
          //             }
          //           });
          //         } else {
          //           console.info("获取用户openId失败");
          //         }
          //       }

          //     })

          //   }
          // })
        }
    }
    ,
    globalData: {
        srvlink:"https://gzmsbweb.gcn99.com",
        userInfo: null,
        chatMsg: []
    }
})